const API = require("../../../utils/api")
const app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        houseId: '',
        gradenDetail: {},
        agreementShow: false,
        agreementJudge: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //2. 获取启动参数 二维码
        if (options && options.scene) {
            //重置登陆状态
            app.globalData.userInfo = {}
            app.globalData.hasUserInfo = false

            let query = {}
            let scene = decodeURIComponent(options.scene).split('&')
            scene.forEach(ele => {
                let key = ele.split('=')[0]
                query[key] = ele.split('=')[1]
            })
            console.log('格式化启动参数', query)
            let globalQuery = {
                userId: query.uid,
                spreadType: query.st,
                type: query.t,
            }
            query.yqid ? globalQuery.gardenId = query.yqid : ''
            query.qyid ? globalQuery.enterpriseId = query.qyid : ''
            app.globalData.inviterUserId = query.uid
            app.globalData.qrQuery = globalQuery
        }

        if (options && options.inviterUserId) {
            app.globalData.inviterUserId = options.inviterUserId
        }

        this.setData({
            houseId: options.id,
            gardenId: options.gardenId,
        })
        this.get_agreement_judge()
        this.get_back_garden_house_detail(options.id, options.gardenId)
        this.get_park_detail(options.gardenId)
    },

    onShow: function () {
        let that = this
        let hasUserInfo = app.globalData.hasUserInfo
        if (!hasUserInfo) {
            wx.reLaunch({
                url: '/pages/login/login?back=/pages/park/house/detail&id=' + that.data.houseId + '&gardenId=' + that.data.gardenId,
            })
        }
    },
    cardEvent(event) {
        const state = event.currentTarget.dataset.state
        const { gradenDetail } = this.data
        if (!this.data.agreementJudge) return this.creatOrder()
        switch (state) {
            case '1': // 查看名片
                wx.navigateTo({ url: `/pages/park/visiting-card/visiting-card?id=${gradenDetail.cardId}` })
                break;
            case '2': // 加微信
                gradenDetail.weChat && gradenDetail.weChat != 'null' ? app.contact(gradenDetail.weChat) : app.contact()
                break;
            case '3': // 拨打电话
                wx.makePhoneCall({ phoneNumber: gradenDetail.phone })
                break;
        }

    },

    onReady: function () {
        this.widget = this.selectComponent('.widget') //初始化wxml转cancas组件
    },

    /**
     * 接口 - 获取园区详情
     */
    get_park_detail: function (gardenId) {
        console.log("get_park_detail-------------")
        let that = this
        API.get_park_detail({
            id: gardenId,
            wxUserid: app.globalData.userInfo.id,
            sourse: 1,
        }).then(res => {
            if (res.code == 200) {
                let detail = res.data
                detail.honorCertification ? detail.honorCertification = detail.honorCertification.split(',') : ''
                detail.serviceTime = detail.serviceTime.substr(0, 10)
                console.log('园区详情', detail)
                that.setData({
                    gradenDetail: detail
                })
            }
        })
    },

    /**
     * 接口 - 获取房源详情
     */
    get_back_garden_house_detail: function (id, gardenId) {
        let that = this
        API.get_back_garden_house_detail({
            id: id,
            gardenId: gardenId,
            sourse: 1,
            userId: app.globalData.userInfo.id
        }).then(res => {
            if (res.code == 200) {
                let detail = res.data
                detail.houseImg = detail.houseImg.split(',')
                detail.content = []
                detail.housingPictures.split(',').forEach(ele => {
                    let item = {
                        name: 'img',
                        attrs: {
                            class: 'item_img',
                            src: ele,
                            style: 'width:100%; height:auto; display:block;'
                        },
                    }
                    detail.content.push(item)
                })
                console.log(detail)
                that.setData({
                    detail
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none'
                })
            }
        })
    },

    /**
     * 接口 - 获取看房确认书
     */
    get_house_viewing_agreement: function () {
        let that = this
        API.get_house_viewing_agreement({
            userId: app.globalData.userInfo.id,
            // userId: 198
        }).then(res => {
            if (res.code == 200) {
                that.setData({
                    agreement: res.data
                })
            } else {
                wx.showToast({
                    title: '预约失败，请稍后重试',
                    icon: 'none'
                })
            }
        })
    },

    /**
     * 事件 - 加微信
     */
    addWxFriend: function () {
        console.log(this.data.gradenDetail)
        if (this.data.gradenDetail.weChat && this.data.gradenDetail.weChat != 'null') {
            app.contact(this.data.gradenDetail.weChat)
        } else {
            app.contact()
        }
    },

    /**
     * 事件 - 电话联系
     */
    callPhone: function () {
        wx.makePhoneCall({
            phoneNumber: this.data.gradenDetail.phone
        })
    },

    /**
     * 路由 - 名片
     */
    routeContact: function () {
        let that = this
        wx.navigateTo({
            url: '/pages/park/visiting-card/visiting-card?id=' + that.data.gradenDetail.cardId,
        })
    },

    /**
     * 事件 - 预约看房
     */
    creatOrder: function () {
        if (this.data.agreementJudge) return this.callPhone()
        this.setData({
            agreementShow: true
        })
        this.get_house_viewing_agreement()
    },

    /**
     * 取消看房
     */
    agreementHidden: function () {
        this.get_agreement_judge()
        this.setData({
            agreementShow: false
        })
    },
    async get_agreement_judge() {
        const res = await API.agreement_judge({
            parkid: this.data.gardenId,
        })
        console.log('get_agreement_judge', res)
        this.data.agreementJudge = res.data
    },
    /**
     * 接口 - 创建工单
     */
    confirmAgreement: function () {
        let that = this
        API.add_park_work_record({
            houseId: that.data.houseId,
            gardenId: that.data.gardenId,
            userId: app.globalData.userInfo.id,
            pageName: '3', //1园区首页 2园区活动 3房源详情
            type: '1'
        }).then(res => {
            if (res.code == 200) {
                wx.showToast({ title: '预约成功' })
                this.get_agreement_judge()
            } else {
                wx.showToast({ title: res.msg, icon: 'none' })
            }

            setTimeout(() => {
                that.setData({
                    agreementShow: false
                })
            }, 1500);
        })
    },

    /**
     * 讲wxml转换成canvas
     */
    shareQrWxml: function () {
        let wxml =
            `
        <view class="container" >
            <view class="item-box red">
            </view>
            <view class="item-box green" >
            <text class="text">yeah!</text>
            </view>
        </view>
        `
        const style = {
            container: {
                width: 300,
                height: 200,
                flexDirection: 'row',
                justifyContent: 'space-around',
                backgroundColor: '#ccc',
                alignItems: 'center',
            },
            itemBox: {
                width: 80,
                height: 60,
            },
            red: {
                backgroundColor: '#ff0000'
            },
            green: {
                backgroundColor: '#00ff00'
            },
            blue: {
                backgroundColor: '#0000ff',
                alignItems: 'center',
                justifyContent: 'center',
            },
            text: {
                width: 80,
                height: 60,
                textAlign: 'center',
                verticalAlign: 'middle',
            },
            img: {
                width: 40,
                height: 40,
                borderRadius: 20,
            }
        }

        //渲染到 canvas，传入 wxml 模板 和 style 对象，返回的容器对象包含布局和样式信息。
        const p1 = this.widget.renderToCanvas({ wxml, style })
        p1.then((res) => {
            this.container = res
            console.log(res)
            this.extraImage()
        })
    },

    /**
     * 提取画布中容器所在区域内容生成相同大小的图片，返回临时文件地址
     */
    extraImage() {
        const p2 = this.widget.canvasToTempFilePath()
        p2.then(res => {
            console.log(res.tempFilePath)
            // this.setData({
            //     src: res.tempFilePath,
            //     width: this.container.layoutBox.width,
            //     height: this.container.layoutBox.height
            // })
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        let that = this
        console.log(that.data.detail)
        return {
            title: that.data.gradenDetail.gardenName + ' ' + that.data.detail.houseArea + '㎡',
            imageUrl: that.data.detail.houseImg[0],
            path: '/pages/park/house/detail?id=' + that.data.houseId + '&gardenId=' + that.data.gradenDetail.id + '&inviterUserId=' + app.globalData.userInfo.id
        }
    },
    onShareTimeline: function () {

    },
})